/*
 * Copyright (c) 2003-2004, Inversoft, All Rights Reserved
 *
 * This software is distribuable under the GNU Lesser General Public License.
 * For more information visit gnu.org.
 */
package org.emergent.antbite.savant;


/**
 * <p>
 * This is a String toolkit.
 * </p>
 *
 * @author Brian Pontarelli
 */
public class StringTools {

    /**
     * Converts the contents of the given String from hexidecimal to an array
     * of bytes. Each character of the String is a single hex value. Therefore,
     * the the pair of characters equals a single byte. This method is little-endian
     * (I think).
     *
     * @param   hexString The hex String to convert
     * @return  An array of bytes
     */
    public static byte [] fromHex(String hexString) {
        int length = hexString.length();

        if ((length & 0x01) != 0) {
            throw new IllegalArgumentException("odd number of characters.");
        }

        byte[] out = new byte[length >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < length; i++) {
            int f = Character.digit(hexString.charAt(j++), 16) << 4;
            f = f | Character.digit(hexString.charAt(j++), 16);
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }
}